package com.ms.pda.messenger

import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.ms.pda.R
import com.ms.pda.activity.storage.OrderOutActivity
import com.ms.pda.base.BaseViewModel
import com.ms.pda.interf.ResponseCallback
import com.ms.pda.model.Constants
import com.ms.pda.model.KeyMap
import com.ms.pda.model.table.StorageOutDO
import com.ms.pda.model.vo.StorageOutVo
import com.ms.pda.net.Request
import com.ms.pda.repository.DB
import com.ms.pda.utils.DialogUtil
import kotlinx.coroutines.launch
import org.apache.commons.io.FileUtils
import java.io.File
import java.lang.StringBuilder
import java.util.function.Consumer


class StorageOutMessenger : BaseViewModel() {

    val storageOrder: MutableLiveData<StorageOutDO?> = MutableLiveData()
    val storageCollection: MutableLiveData<MutableList<StorageOutVo>> =
        MutableLiveData(mutableListOf())


    suspend fun getStorageOutCode(
        orderNumber: String?,
        consumer: Consumer<MutableList<StorageOutDO>>
    ) {
        if (orderNumber.isNullOrEmpty()) {
            Log.i(OrderOutActivity.TAG, "getStorageOutCode Empty")
            consumer.accept(mutableListOf())
        } else {
            DB.queryStorageOut(orderNumber).collect {
                Log.i(OrderOutActivity.TAG, "getStorageOutCode size:${it.size}")
                consumer.accept(it.toMutableList())
            }
        }
    }

    suspend fun saveCatch(newList: MutableList<StorageOutDO>) {
        DB.insertStorageOut(newList)
    }

    suspend fun clearCatch() {
        DB.clearStorageOut()
    }


    /**
     * 提交出库
     */
    suspend fun submitOutOfStock(
        activity: AppCompatActivity,
        orderNumber: String,
        consumer: Consumer<Boolean>
    ) {
        DB.queryStorageOut(orderNumber).collect { list ->
            val stringBuilder = StringBuilder()
            list.forEachIndexed { index, storageOutDO ->
                if (index != 0) {
                    stringBuilder.append("\n")
                }
                stringBuilder.append(storageOutDO.orderNo)
                    .append(",")
                    .append(storageOutDO.rfidId)
                    .append(",")
                    .append(storageOutDO.createTime)
            }
            val orderFile = File(activity.cacheDir, "${orderNumber}.bat")
            if (orderFile.exists()) {
                Log.d(OrderOutActivity.TAG, "文件已经存在删除 orderFile:${orderFile.absolutePath}")
                orderFile.delete()
            }
            try {
                FileUtils.write(orderFile, stringBuilder.toString())
                Log.d(
                    OrderOutActivity.TAG,
                    "数据已经保存的文件 orderFile:${orderFile.absolutePath}"
                )
            } catch (e: Exception) {
                e.printStackTrace()
                handleResponseError(e, KeyMap.OUT_OF_STOCK.value)
            }
            if (orderFile.exists()) {
                Request.upload(activity, orderFile, object : ResponseCallback<Boolean> {
                    override fun onSuccess(t: Boolean) {
                        Log.d(
                            OrderOutActivity.TAG,
                            "文件上传成功 orderFile:${orderFile.absolutePath}"
                        )
                        orderFile.delete()
                        consumer.accept(t)
                    }

                    override fun onFailed(throwable: Throwable) {
                        Log.d(
                            OrderOutActivity.TAG,
                            "文件上传失败 orderFile:${orderFile.absolutePath}"
                        )
                        throwable.printStackTrace()
                        consumer.accept(false)
                        handleResponseError(throwable, KeyMap.OUT_OF_STOCK.value)
                    }
                })
            }
        }
    }


    /**
     * 提交成功重置
     */
    suspend fun submittedReset() {
        DB.clearStorageOut()
        storageOrder.value = null
        storageCollection.value = mutableListOf()
        SPUtils.getInstance().put(Constants.lastScanOrder, "")
    }

    /**
     * 清除数据
     */
    suspend fun reset(activity: AppCompatActivity) {
        viewModelScope.launch {
            submittedReset()
        }
    }
}